package ls

import (
	"fmt"
	"os"
	"strings"

	"gitee.com/eeppee_admin/go-tuiftp/reuse"
	"github.com/jlaffaye/ftp"
)

func Ls(path string) {
	// path格式: [站点名称]:[远程路径]
	arr := strings.Split(path, ":")
	if len(arr) != 2 {
		// example: ls test:/
		fmt.Println("远程路径格式错误,格式为 -> [站点名称]:[远程路径]")
		os.Exit(-1)
	}

	sysConfig := &reuse.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Println("error: ls cmd, Failed to read config file:", err)
		os.Exit(-1)
	}
	var mySite *reuse.SiteConfig
	for _, site := range sysConfig.Sites {
		if site.Name == arr[0] {
			mySite = &site
			break
		}
	}

	if mySite == nil {
		fmt.Printf("error: ls cmd, 没有找到%s的配置\n", arr[0])
		os.Exit(-1)
	}

	ftpClient, err := reuse.NewFtpClient(*mySite)
	if err != nil {
		fmt.Println("error: ls cmd, Failed to connect: ", err)
		os.Exit(-1)
	}
	entries, err := ftpClient.Conn.List(arr[1])
	if err != nil {
		fmt.Println("error: ls cmd, Failed to list: ", err)
		os.Exit(-1)
	}
	for _, entry := range entries {
		// 大小 修改时间 文件的类型 文件名称
		fmt.Printf("%-13s %-15s %-5s %s \n", reuse.HumanReadableSize(entry.Size),
			entry.Time.Format("2006-01-02 15:04:05"),
			reuse.If(entry.Type == ftp.EntryTypeFolder, "文件夹", "文件"),
			entry.Name)
	}
}
